package com.example.ivideo_2211a

import android.Manifest
import android.content.pm.PackageManager
import android.hardware.Camera
import android.os.Bundle
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

/**
 * 相机测试Activity
 * 用于测试相机功能是否正常工作
 */
class CameraTestActivity : AppCompatActivity(), SurfaceHolder.Callback {
    
    private lateinit var surfaceView: SurfaceView
    private var camera: Camera? = null
    
    companion object {
        private const val CAMERA_PERMISSION_REQUEST = 100
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera_test)
        
        surfaceView = findViewById(R.id.surfaceView)
        surfaceView.holder.addCallback(this)
        
        checkCameraPermission()
    }
    
    private fun checkCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.CAMERA),
                CAMERA_PERMISSION_REQUEST
            )
        } else {
            initializeCamera()
        }
    }
    
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        when (requestCode) {
            CAMERA_PERMISSION_REQUEST -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "相机权限已授予", Toast.LENGTH_SHORT).show()
                    initializeCamera()
                } else {
                    Toast.makeText(this, "需要相机权限才能使用此功能", Toast.LENGTH_LONG).show()
                }
            }
        }
    }
    
    override fun surfaceCreated(holder: SurfaceHolder) {
        // Surface创建后初始化相机
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            initializeCamera()
        }
    }
    
    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        // Surface尺寸改变时重新配置相机
        if (holder.surface == null) return
        
        try {
            camera?.stopPreview()
        } catch (e: Exception) {
            // 忽略异常
        }
        
        try {
            camera?.setPreviewDisplay(holder)
            camera?.startPreview()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    override fun surfaceDestroyed(holder: SurfaceHolder) {
        // Surface销毁时释放相机
        releaseCamera()
    }
    
    private fun initializeCamera() {
        try {
            // 获取前置摄像头（如果有的话，否则使用后置摄像头）
            val cameraId = getFrontCameraId()
            camera = Camera.open(cameraId)
            
            // 设置相机参数
            val parameters = camera?.parameters
            parameters?.let {
                // 设置预览尺寸
                val previewSizes = it.supportedPreviewSizes
                if (previewSizes.isNotEmpty()) {
                    val previewSize = previewSizes[0] // 使用第一个支持的尺寸
                    it.setPreviewSize(previewSize.width, previewSize.height)
                }
                
                // 设置对焦模式（如果支持）
                val focusModes = it.supportedFocusModes
                if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
                    it.focusMode = Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO
                } else if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                    it.focusMode = Camera.Parameters.FOCUS_MODE_AUTO
                }
                
                camera?.parameters = it
            }
            
            // 设置预览方向
            camera?.setDisplayOrientation(0)
            
            Toast.makeText(this, "相机初始化成功", Toast.LENGTH_SHORT).show()
            
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "相机初始化失败: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }
    
    private fun getFrontCameraId(): Int {
        val numberOfCameras = Camera.getNumberOfCameras()
        for (i in 0 until numberOfCameras) {
            val info = Camera.CameraInfo()
            Camera.getCameraInfo(i, info)
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                return i
            }
        }
        // 如果没有前置摄像头，使用默认摄像头
        return 0
    }
    
    private fun releaseCamera() {
        try {
            camera?.stopPreview()
            camera?.release()
            camera = null
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        releaseCamera()
    }
}
